package com.kingwood.algorithm.test;

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;

/**
 * @Author 22025812
 * @Description: TODO
 * @Date: 2024/2/28 17:08
 * @Modified By：
 * @Version 1.0
 */
public class QueueRelated {

    /**
     * 执行任务赚积分*
     * https://fcqian.blog.csdn.net/article/details/134719131
     * @param tasks
     * @param times
     * @return
     */
    public static int getTaskScore(int[][] tasks, int times) {
        // 按照任务截止时间升序
        Arrays.sort(tasks, (a, b)-> a[0] - b[0]);
        // 优先级队列，按照积分排序，积分越小，优先级越高，目的是替换掉最少积分的工单
        // 小根堆，越小越在上面（优先出队列）
        PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> a - b);

        int curTime = 0;
        int ans = 0;

        for (int[] task : tasks) {
            int endTime = task[0];
            int score = task[1];

            if (curTime < endTime) {
                pq.offer(score);
                ans += score;
                curTime++;
            } else {
                if (pq.size() == 0) {
                    continue;
                }

                int min_score = pq.peek();
                if (score > min_score) {
                    pq.poll();
                    pq.offer(score);
                    ans += score - min_score;
                }
            }
        }

        while (pq.size() > times && times > 0) {
            ans -= pq.poll();
        }

        return ans;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int t = scanner.nextInt();
        int[][] tasks = new int[n][2];

        for (int i=0; i<n; i++) {
            tasks[i][0] = scanner.nextInt();
            tasks[i][1] = scanner.nextInt();
        }

        System.out.println(getTaskScore(tasks, t));
    }
}
